package com.sbtr.common.file.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ListUtils;
import com.sbtr.common.file.utils.AbstractImportInterface;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * EasyExcel不创建数据对象的读
 */
@Slf4j
public class AbstractNoModelDataListener extends AnalysisEventListener<LinkedHashMap<Integer, String>> {

    /**
     * 每隔1000条解析
     */
    private static final int BATCH_COUNT = 1000;
    private List<LinkedHashMap<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);;
    public List<LinkedHashMap<Integer, String>> resultDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);;
    public List<String> titleList= new ArrayList<>();
    private AbstractImportInterface importInterface;
    private Map<String, String> params;

    /**
     * 初始化业务处理的service层和其他业务参数
     * @param importInterface 处理业务的service层
     * @param params 其他业务参数
     */
    public AbstractNoModelDataListener(AbstractImportInterface importInterface, Map<String, String> params) {
        this.importInterface = importInterface;
        this.params = params;
    }

    // 默认跳过第一行（通常情况下第一行为标题栏）
    @Override
    public void invoke(LinkedHashMap<Integer, String> data, AnalysisContext context) {

        // 通过 AnalysisContext 对象还可以获取当前 sheet，当前行等数据
        // 若有跳过行数需求，可写个钩子进行处理
//    	context.getCurrentRowNum()

        log.debug("解析到一条数据:{}", data.toString());
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);;
        }
    }
    //表头是从该方法读取
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
//        System.out.println("表头:"+headMap.get(1).getStringValue());
        for (ReadCellData<?> r:headMap.values()) {
            titleList.add(r.getStringValue());
        }

        super.invokeHead(headMap, context);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 存储
     */
    private void saveData() {
        log.info("{}条数据，开始累加！", cachedDataList.size());
        this.resultDataList.addAll(importInterface.analyze(params, cachedDataList));
        log.info("存储成功！");
    }

    /**
     * 转换成集合嵌套数组字符串
     * @return
     */
    public List<String[]> getListStr(){
        List<String[]> list = new ArrayList<>();

        for (int i = 0; i < this.resultDataList.size(); i++) {
            String[] str=new String[this.resultDataList.get(i).size()];
            for (int j = 0; j < this.resultDataList.get(i).size(); j++) {
                str[j]=this.resultDataList.get(i).get(j);
            }
            list.add(str);
        }
        return list;
    }
}
